package cn.merryyou.security.security;

import cn.merryyou.security.entity.po.LoginUser;
import cn.merryyou.security.mappers.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 获取用户信息和权限返回
 *
 * @author liucancan
 * @date 2018/12/19
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取登录人用户信息
        LoginUser user = userDao.findByUsername(username);
        if (user == null) {
            throw new AuthenticationCredentialsNotFoundException("用户不存在");
        }
        // 封装成spring security的user返回
        return new User(user.getUserName(), user.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
    }
}
